import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import '../../models/circle_models.dart';
import '../../core/controller/im_controller.dart'; // 添加这行导入
import 'package:openim_common/openim_common.dart'; // 如果还没有导入的话

class NotificationModel {
  final String userName;
  final String userAvatar;
  final String timeAgo;
  final String content;
  final List<String> images;

  NotificationModel({
    required this.userName,
    required this.userAvatar,
    required this.timeAgo,
    required this.content,
    required this.images,
  });
}

class NotificationLogic extends GetxController {
  // 通知相关
  final notifications = <PostNotification>[].obs;
  final unreadNotificationCount = 0.obs;
  final posts = <CirclePost>[].obs;
  final allTags = <PostTag>[].obs;
  final availableTags = <PostTag>[].obs;
  final selectedTagId = ''.obs;
  final currentCircleType = CircleType.city.obs;
  final searchKeyword = ''.obs;
  final imLogic = Get.find<IMController>(); // 添加这行
  final isRefreshing = false.obs;
  // 添加一个用于通知UI滚动的响应式变量
  final scrollToPostId = ''.obs;

  // 添加圈子相关变量
  final allCircles = <Circle>[].obs;
  final isLoadingCircles = false.obs;
  
  // 添加发布帖子相关的图片状态
  final selectedImages = <String>[].obs; // 存储已上传的图片URL
  final selectedImageFiles = <XFile>[].obs; // 存储本地选择的图片文件
  
  // 添加发布帖子相关的视频状态
  final selectedVideoFile = Rxn<XFile>(); // 存储本地选择的视频文件
  final videoThumbnailPath = Rxn<String>(); // 存储视频缩略图路径
  
  // 添加发布帖子相关的位置状态
  final selectedLocation = Rxn<Position>(); // 存储选择的位置
  final selectedLocationAddress = ''.obs; // 存储选择的位置地址
  @override
  void onInit() {
    super.onInit();
    // _initializeDefaultTags();
    loadNotifications();
    // loadPosts();
    // 从后台加载标签
    loadTagsFromBackend();
    // 从后台加载所有圈子信息
    loadCirclesFromBackend();
  }

   /// 从后台加载所有圈子信息
  Future<void> loadCirclesFromBackend() async {
    if (isLoadingCircles.value) return; // 防止重复加载
    
    try {
      isLoadingCircles.value = true;
      final response = await Apis.getAllCircles();
      print("圈子数据返回值: $response");
      
      if (response != null) {
        // 清空现有圈子
        allCircles.clear();
        debugPrint('从后台加载圈子: $response');
        
        // 解析后台返回的圈子数据
        final circlesData = response['data'] as List?;
        if (circlesData != null) {
          for (var circleJson in circlesData) {
            try {
              // 根据后台数据结构创建Circle对象
              final circle = Circle.fromJson(circleJson);
              allCircles.add(circle);
            } catch (e) {
              print('解析圈子失败: $e, 圈子数据: $circleJson');
            }
          }
        }
        
        print('成功加载 ${allCircles.length} 个圈子');
        
        // 可以根据需要进行圈子排序
        allCircles.sort((a, b) {
          // 按类型排序：城市圈 -> 国家圈 -> 全球圈
          const typeOrder = {
            CircleType.city: 0,
            CircleType.country: 1,
            CircleType.global: 2,
          };
          return (typeOrder[a.type] ?? 3).compareTo(typeOrder[b.type] ?? 3);
        });
        
      }
    } catch (e) {
      print('从后台加载圈子失败: $e');
    } finally {
      isLoadingCircles.value = false;
    }
  }
   
  // 根据类型获取圈子
  Circle? getCircleByType(Circltype) {
    try {
      return allCircles.firstWhere((circle) => circle.type == Circltype);
    } catch (e) {
      return null;
    }
  }

  /// 获取所有激活的圈子
  List<Circle> getActiveCircles() {
    return allCircles.where((circle) => circle.isActive).toList();
  }

  /// 刷新圈子信息
  Future<void> refreshCircles() async {
    await loadCirclesFromBackend();
  }
   
   /// 从后台加载所有标签
  Future<void> loadTagsFromBackend() async {
    try {
      final response = await Apis.getTags();
      print("标签数据返回值: $response");
      
      if (response != null) {
        // 清空现有标签
        allTags.clear();
        debugPrint('从后台加载标: $response');
        // 解析后台返回的标签数据
        final tagsData = response['data'] as List?;
        if (tagsData != null) {
          for (var tagJson in tagsData) {
            try {
              // 根据后台数据结构创建PostTag对象
              final tag = PostTag(
                id: tagJson['id'].toString(),
                name: tagJson['name'] ?? '',
                type: _mapCircleType(tagJson['circle_id']), // 根据circle_id映射圈子类型
                color: tagJson['color'],
                isDefault: false, // 后台标签都不是默认标签
              );
              allTags.add(tag);
            } catch (e) {
              print('解析标签失败: $e, 标签数据: $tagJson');
            }
          }
        }
        // 更新可用标签
        _updateAvailableTags();
        print('成功加载 ${allTags.length} 个标签');
      }
    } catch (e) {
      print('从后台加载标签失败: $e');
      // 如果加载失败，使用默认标签作为备选
      // _initializeDefaultTags();
    }
  }

  /// 根据circle_id映射圈子类型
  CircleType _mapCircleType(dynamic circleId) {
    if (circleId == null) return CircleType.city;
    
    final id = circleId is String ? int.tryParse(circleId) ?? 1 : circleId as int;
    switch (id) {
      case 1:
        return CircleType.city;
      case 2:
        return CircleType.country;
      case 3:
        return CircleType.global;
      default:
        return CircleType.city;
    }
  }

  // 加载示例通知数据
  void loadNotifications() {
    final sampleNotifications = [
      // PostNotification(
      //   id: 'notif_1',
      //   postId: 'post_1',
      //   fromUserId: 'user_2',
      //   fromUserName: '李明',
      //   fromUserAvatar: 'https://example.com/avatar2.jpg',
      //   type: NotificationType.like,
      //   content: '赞了你的帖子',
      //   createdAt: DateTime.now().subtract(const Duration(minutes: 5)),
      //   targetContent: '今天天气真不错...',
      // ),
      // PostNotification(
      //   id: 'notif_2',
      //   postId: 'post_2',
      //   fromUserId: 'user_3',
      //   fromUserName: '王芳',
      //   fromUserAvatar: 'https://example.com/avatar3.jpg',
      //   type: NotificationType.comment,
      //   content: '评论了你的帖子',
      //   createdAt: DateTime.now().subtract(const Duration(hours: 1)),
      //   targetContent: '分享一些生活感悟...',
      // ),
      // PostNotification(
      //   id: 'notif_3',
      //   postId: 'post_3',
      //   fromUserId: 'user_4',
      //   fromUserName: '张伟',
      //   fromUserAvatar: 'https://example.com/avatar4.jpg',
      //   type: NotificationType.mention,
      //   content: '在帖子中提到了你',
      //   createdAt: DateTime.now().subtract(const Duration(hours: 2)),
      //   targetContent: '@张三 你觉得这个怎么样？',
      // ),
    ];
    
    // notifications.assignAll(sampleNotifications);
    _updateUnreadCount();
  }

  // 更新未读通知数量
  void _updateUnreadCount() {
    unreadNotificationCount.value = notifications.where((n) => !n.isRead).length;
  }

  // 标记通知为已读
  void markNotificationAsRead(String notificationId) {
    final index = notifications.indexWhere((n) => n.id == notificationId);
    if (index != -1) {
      final notification = notifications[index];
      notifications[index] = PostNotification(
        id: notification.id,
        postId: notification.postId,
        fromUserId: notification.fromUserId,
        fromUserName: notification.fromUserName,
        fromUserAvatar: notification.fromUserAvatar,
        type: notification.type,
        content: notification.content,
        createdAt: notification.createdAt,
        isRead: true,
        targetContent: notification.targetContent,
      );
      _updateUnreadCount();
    }
  }

  // 标记所有通知为已读
  void markAllNotificationsAsRead() {
    for (int i = 0; i < notifications.length; i++) {
      final notification = notifications[i];
      if (!notification.isRead) {
        notifications[i] = PostNotification(
          id: notification.id,
          postId: notification.postId,
          fromUserId: notification.fromUserId,
          fromUserName: notification.fromUserName,
          fromUserAvatar: notification.fromUserAvatar,
          type: notification.type,
          content: notification.content,
          createdAt: notification.createdAt,
          isRead: true,
          targetContent: notification.targetContent,
        );
      }
    }
    _updateUnreadCount();
  }

  // 删除通知
  void deleteNotification(String notificationId) {
    notifications.removeWhere((n) => n.id == notificationId);
    _updateUnreadCount();
  }

  // 获取未读通知
  List<PostNotification> get unreadNotifications {
    return notifications.where((n) => !n.isRead).toList();
  }

  void switchCircleType(CircleType type) {
    debugPrint("switch:$type");
    currentCircleType.value = type;
    posts.clear();
    selectedTagId.value = '';
    _updateAvailableTags();
    refreshPosts(type);
  }

  void _updateAvailableTags() {
    availableTags.value = allTags
        .where((tag) => tag.type == currentCircleType.value)
        .toList();
  }

  List<CirclePost> getPostsByType(CircleType type) {
    debugPrint("getPostsByType:$type");
    var filteredPosts = posts.where((post) {
      // 按圈子类型筛选
      bool hasTypeTag = post.circleType == type;
      if (!hasTypeTag) return false;
      
      // 按选中的标签筛选
      if (selectedTagId.value.isNotEmpty) {
        bool hasSelectedTag = post.tags.any((tag) => tag.id == selectedTagId.value);
        if (!hasSelectedTag) return false;
      }
      
      // 按搜索关键词筛选
      if (searchKeyword.value.isNotEmpty) {
        bool matchesKeyword = post.content.toLowerCase().contains(searchKeyword.value.toLowerCase()) ||
                             post.userName.toLowerCase().contains(searchKeyword.value.toLowerCase()) ||
                             post.tags.any((tag) => tag.name.toLowerCase().contains(searchKeyword.value.toLowerCase()));
        if (!matchesKeyword) return false;
      }
      
      return true;
    }).toList();
    
    // 按时间倒序排列
    filteredPosts.sort((a, b) => b.createdAt.compareTo(a.createdAt));
    return filteredPosts;
  }

  List<PostTag> getTagsByType(CircleType type) {
    return allTags.where((tag) => tag.type == type).toList();
  }

  void selectTag(String tagId) {
    print('DEBUG: selectTag called with tagId: $tagId');
    print('DEBUG: Current selectedTagId before: ${selectedTagId.value}');
    print('DEBUG: Available tags: ${availableTags.map((t) => '${t.name}(${t.id})').toList()}');
    
    selectedTagId.value = tagId;
    
    print('DEBUG: selectedTagId after update: ${selectedTagId.value}');
    
    // 强制触发UI更新
    update();
  }

  /// 搜索帖子：调用后端搜索接口并更新列表
  Future<void> searchPosts(String keyword) async {
    searchKeyword.value = keyword;
    final kw = keyword.trim();
    if (kw.isEmpty) {
      // 关键词为空时恢复当前圈子帖子
      await refreshPosts(currentCircleType.value);
      return;
    }
  
    try {
      final circleId = _getCircleId(currentCircleType.value).toString();
      final response = await Apis.searchPosts(
        keyword: kw,
        page: 1,
        pageSize: 20,
        circleId: circleId, // 让搜索结果与当前圈子一致
      );
  
      final postsData = response['posts'] as List?;
      if (postsData == null) {
        IMViews.showToast('搜索失败：返回数据为空');
        return;
      }

      if (postsData.isEmpty) {
        posts.clear();
        IMViews.showToast('没有找到与“$kw”相关的帖子');
        return;
      }
  
      // 清空现有帖子
      posts.clear();
  
      // 第一步：收集所有OpenIM用户ID
      final Set<String> openimUserIds = {};
      for (var postJson in postsData) {
        final openimUserId = postJson['user']?['openim_user_id'];
        if (openimUserId != null && openimUserId.isNotEmpty) {
          openimUserIds.add(openimUserId);
        }
      }
  
      // 第二步：批量获取OpenIM用户信息（缓存+在线补拉）
      Map<String, dynamic> openimUserInfoMap = {};
      if (openimUserIds.isNotEmpty) {
        try {
          final cachedList = await OpenIM.iMManager.userManager
              .getUsersInfoWithCache(openimUserIds.toList());
          final Set<String> missingIds = {};
          for (final userInfo in cachedList) {
            final id = userInfo.userID;
            if (id != null) {
              final nickname = userInfo.nickname;
              final faceURL = userInfo.faceURL;
              openimUserInfoMap[id] = {
                'nickname': nickname,
                'faceURL': faceURL,
              };
              if ((nickname == null || nickname.isEmpty) ||
                  (faceURL == null || faceURL.isEmpty)) {
                missingIds.add(id);
              }
            }
          }
          for (final id in openimUserIds) {
            if (!openimUserInfoMap.containsKey(id)) {
              missingIds.add(id);
            }
          }
          if (missingIds.isNotEmpty) {
            final onlineList = await OpenIM.iMManager.userManager
                .getUsersInfo(userIDList: missingIds.toList());
            for (final userInfo in onlineList) {
              final id = userInfo.userID;
              if (id != null) {
                final nickname =
                    userInfo.nickname ?? userInfo.simpleUserInfo?.nickname;
                final faceURL =
                    userInfo.faceURL ?? userInfo.simpleUserInfo?.faceURL;
                final existing = openimUserInfoMap[id];
                openimUserInfoMap[id] = {
                  'nickname': (nickname != null && nickname.isNotEmpty)
                      ? nickname
                      : (existing?['nickname']),
                  'faceURL': (faceURL != null && faceURL.isNotEmpty)
                      ? faceURL
                      : (existing?['faceURL']),
                };
              }
            }
          }
        } catch (e) {
          debugPrint('批量获取OpenIM用户信息失败: $e');
        }
      }
  
      // 第三步：构建帖子对象
      for (var postJson in postsData) {
        final openimUserId = postJson['user']?['openim_user_id'];
        String userName = postJson['user']?['nickname'] ?? '未知用户';
        String userAvatar = postJson['user']?['avatar'] ?? '';
        if (openimUserId != null && openimUserInfoMap.containsKey(openimUserId)) {
          final openimInfo = openimUserInfoMap[openimUserId];
          userName = openimInfo['nickname'] ?? userName;
          userAvatar = openimInfo['faceURL'] ?? userAvatar;
        }
  
        final post = CirclePost(
          id: postJson['id'].toString(),
          userId: postJson['user_id'] ?? '',
          userName: userName,
          userAvatar: userAvatar,
          content: postJson['content'] ?? '',
          images: List<String>.from(postJson['images'] ?? []),
          videos: List<String>.from(postJson['videos'] ?? []),
          tags: parseTags(postJson['tags']),
          createdAt: DateTime.tryParse(postJson['created_at'] ?? '') ?? DateTime.now(),
          likeCount: postJson['like_count'] ?? 0,
          isLiked: postJson['is_liked'] ?? false,
          isBookmarked: postJson['is_collected'] ?? false,
          commentCount: postJson['comment_count'] ?? 0,
          shareCount: postJson['share_count'] ?? 0,
          circleId: postJson['circle_id'],
          circleName: postJson['circle']?['name'],
          circleType: _mapCircleTypeFromString(postJson['circle']?['type']?.toString() ?? 'city'),
          locationLatitude: (() {
            final v = postJson['location_latitude'];
            if (v is num) return v.toDouble();
            if (v is String) return double.tryParse(v);
            return null;
          })(),
          locationLongitude: (() {
            final v = postJson['location_longitude'];
            if (v is num) return v.toDouble();
            if (v is String) return double.tryParse(v);
            return null;
          })(),
          locationAddress: postJson['location_address'],
        );
        posts.add(post);
      }
  
      // 可选：提示或触发 UI 更新
      update();
    } catch (e) {
      IMViews.showToast('搜索失败: $e');
    }
  }
  void toggleLike(String postId) async {
    final postIndex = posts.indexWhere((post) => post.id == postId);
    if (postIndex != -1) {
      final post = posts[postIndex];
      final wasLiked = post.isLiked;
      
      try {
        // 先更新本地状态以提供即时反馈
        final newPost = CirclePost(
          id: post.id,
          userId: post.userId,
          userName: post.userName,
          userAvatar: post.userAvatar,
          content: post.content,
          images: post.images,
          videos: post.videos,
          tags: post.tags,
          createdAt: post.createdAt,
          likeCount: wasLiked ? post.likeCount - 1 : post.likeCount + 1,
          commentCount: post.commentCount,
          shareCount: post.shareCount,
          isLiked: !wasLiked,
          isBookmarked: post.isBookmarked,
          // 保持圈子相关字段
          circleId: post.circleId,
          circleName: post.circleName,
          circleType: post.circleType,
          circle: post.circle,
          // 保持位置相关字段
          locationLatitude: post.locationLatitude,
          locationLongitude: post.locationLongitude,
          locationAddress: post.locationAddress,
        );
        posts[postIndex] = newPost;
        update(); // 立即触发UI更新
        
        // 调用后端API
        if (wasLiked) {
          await Apis.unlikePost(postId);
        } else {
          await Apis.likePost(postId);
        }
      } catch (e) {
        // 如果API调用失败，恢复原始状态
        posts[postIndex] = post;
        update(); // 恢复状态后也要触发UI更新
        IMViews.showToast('操作失败: $e');
        debugPrint('点赞操作失败: $e');
      }
    }
  }

  void toggleBookmark(String postId) async {
    final postIndex = posts.indexWhere((post) => post.id == postId);
    if (postIndex != -1) {
      final post = posts[postIndex];
      final wasBookmarked = post.isBookmarked;
      
      try {
        // 先更新本地状态以提供即时反馈
        final newPost = CirclePost(
          id: post.id,
          userId: post.userId,
          userName: post.userName,
          userAvatar: post.userAvatar,
          content: post.content,
          images: post.images,
          videos: post.videos,
          tags: post.tags,
          createdAt: post.createdAt,
          likeCount: post.likeCount,
          commentCount: post.commentCount,
          shareCount: post.shareCount,
          isLiked: post.isLiked,
          isBookmarked: !wasBookmarked,
          // 保持圈子相关字段
          circleId: post.circleId,
          circleName: post.circleName,
          circleType: post.circleType,
          circle: post.circle,
          // 保持位置相关字段
          locationLatitude: post.locationLatitude,
          locationLongitude: post.locationLongitude,
          locationAddress: post.locationAddress,
        );
        posts[postIndex] = newPost;
        update(); // 立即触发UI更新
        debugPrint("toggleBookmark: postId = $postId, wasBookmarked = $wasBookmarked");
        // 调用后端API
        if (wasBookmarked) {
          await Apis.uncollectPost(postId);
        } else {
          await Apis.collectPost(postId);
        }
      } catch (e) {
        // 如果API调用失败，恢复原始状态
        posts[postIndex] = post;
        update(); // 恢复状态后也要触发UI更新
        IMViews.showToast('操作失败: $e');
        debugPrint('收藏操作失败: $e');
      }
    }
  }

  Future<void> sharePost(String postId) async {
    final postIndex = posts.indexWhere((post) => post.id == postId);
    if (postIndex == -1) {
      IMViews.showToast('帖子不存在');
      return;
    }

    try {
      // 调用后端分享接口
      final resp = await Apis.sharePost(postId);
      Map<dynamic, dynamic>? data;
      if (resp is Map) {
        final d = resp['data'] ?? resp;
        if (d is Map) data = d as Map;
      }
      final String? path = data != null ? (data['path'] as String?) : null;

      // 解析后端返回的最新分享计数
      int? updatedCount;
      final sc = data != null ? data['share_count'] : null;
      if (sc is int) {
        updatedCount = sc;
      } else if (sc is String) {
        final parsed = int.tryParse(sc);
        if (parsed != null) updatedCount = parsed;
      }

      // 更新本地分享计数（优先使用后端返回的最新计数）
      final post = posts[postIndex];
      final newPost = CirclePost(
        id: post.id,
        userId: post.userId,
        userName: post.userName,
        userAvatar: post.userAvatar,
        content: post.content,
        images: post.images,
        videos: post.videos,
        tags: post.tags,
        createdAt: post.createdAt,
        likeCount: post.likeCount,
        commentCount: post.commentCount,
        shareCount: updatedCount ?? (post.shareCount + 1),
        isLiked: post.isLiked,
        isBookmarked: post.isBookmarked,
        circleId: post.circleId,
        circleName: post.circleName,
        circleType: post.circleType,
        circle: post.circle,
        locationLatitude: post.locationLatitude,
        locationLongitude: post.locationLongitude,
        locationAddress: post.locationAddress,
      );
      posts[postIndex] = newPost;
      update();

      // 组合完整链接并复制到剪贴板
      final String base = Config.domainBackendUrl; // 当前域名
      String? fullLink;
      if (path != null && path.isNotEmpty) {
        try {
          fullLink = Uri.parse(base).resolve(path).toString();
        } catch (_) {
          fullLink = null;
        }
      }
      if (fullLink != null) {
        await Clipboard.setData(ClipboardData(text: fullLink));
        IMViews.showToast('分享链接已复制');
        debugPrint('Share link: $fullLink');
      } else {
        IMViews.showToast('未获取到分享链接');
      }
    } catch (e, s) {
      debugPrint('分享失败: $e\n$s');
      IMViews.showToast('分享失败: $e');
    }
  }

    // 删除帖子
  Future<void> deletePost(String postId) async {
    try {
      // 调用后端API删除帖子
      final response = await Apis.deletePost(postId);
      debugPrint(response.toString());
      posts.removeWhere((post) => post.id == postId);
    } catch (e) {
      IMViews.showToast('删除失败: $e');
    }
  }

   // 编辑帖子
  Future<void> updatePost(String postId, String newContent, List<PostTag> newTags) async {
    try {
      // 找到要编辑的帖子
      final postIndex = posts.indexWhere((post) => post.id == postId);
      if (postIndex == -1) {
        IMViews.showToast('帖子不存在');
        return;
      }

      final originalPost = posts[postIndex];
      
      // 准备更新数据
      final tagIds = newTags.map((tag) {
        try {
          return int.parse(tag.id);
        } catch (e) {
          return tag.id.hashCode.abs() % 1000;
        }
      }).toList();

      // 调用后端API更新帖子
      final response = await Apis.updatePost(
        postId: postId,
        content: newContent,
        tagIds: tagIds,
      );  

      // 更新本地帖子数据
      final updatedPost = CirclePost(
        id: originalPost.id,
        userId: originalPost.userId,
        userName: originalPost.userName,
        userAvatar: originalPost.userAvatar,
        content: newContent,
        images: originalPost.images,
        videos: originalPost.videos,
        tags: newTags,
        createdAt: originalPost.createdAt,
        likeCount: originalPost.likeCount,
        commentCount: originalPost.commentCount,
        shareCount: originalPost.shareCount,
        isLiked: originalPost.isLiked,
        isBookmarked: originalPost.isBookmarked,
        circleType: originalPost.circleType,
        circleId: originalPost.circleId,
        circleName: originalPost.circleName,
      );
      
      posts[postIndex] = updatedPost;
      debugPrint("更新后的帖子: $updatedPost");
    } catch (e) {
      IMViews.showToast('更新失败: $e');
    }
  }

  // 检查是否为当前用户的帖子
  bool isCurrentUserPost(String postUserId) {
    debugPrint("POST USER ID: $postUserId");
    debugPrint("CURRENT USER ID: ${DataSp.getLoginCertificate()?.userID}");
    return postUserId == DataSp.getLoginCertificate()?.userID;
  }

  // 获取帖子显示的用户昵称
  String getPostDisplayName(CirclePost post) {
    if (isCurrentUserPost(post.userId)) {
      // 如果是当前用户的帖子，显示当前用户的昵称
      return imLogic.userInfo.value.nickname ?? '我';
    } else {
      // 如果不是当前用户的帖子，显示原始用户名
      return post.userName;
    }
  }

  // 获取通知显示的用户昵称
  String getNotificationDisplayName(PostNotification notification) {
    if (notification.fromUserId == DataSp.getLoginCertificate()?.userID) {
      // 如果是当前用户的通知，显示当前用户的昵称
      return imLogic.userInfo.value.nickname ?? '我';
    } else {
      // 如果不是当前用户的通知，显示原始用户名
      return notification.fromUserName;
    }
  }


  // 发布帖子（接受CirclePost对象）
  Future<void> publishPost(CirclePost post, CircleType circleType) async {
    // 将帖子添加到本地列表
    posts.insert(0, post);
    
    // 可选：调用API发布到服务器
    await _publishPostToServer(post, circleType);
  }
  // 发布帖子到服务器
  Future<void> _publishPostToServer(CirclePost post, CircleType circleType) async {
  try {
      // 根据圈子类型从已加载的圈子信息中获取真实的circleId
      final circle = getCircleByType(circleType);
      if (circle == null) {
        // 如果没有找到对应的圈子，可能是数据还未加载完成
        IMViews.showToast('圈子信息加载中，请稍后重试');
        return;
      }
      
      final int circleId = circle.id;
      debugPrint("使用圈子ID: $circleId, 圈子名称: ${circle.name}");
      
      debugPrint("POST:${post.tags}");
    // 从post.tags中提取标签ID并转换为int数组
    List<int> tagIds = [];
    if (post.tags.isNotEmpty) {
      tagIds = post.tags.map((tag) {
        debugPrint(tag.id.toString());
        // 如果tag.id是字符串格式的数字，则转换；否则使用hash值或默认值
        try {
          debugPrint("TAG:"+tag.id);
          return int.parse(tag.id);
        } catch (e) {
          debugPrint("TAG: NO  PARSER");
          // 如果无法解析，可以使用tag.id的hash值或分配默认值
          return tag.id.hashCode.abs() % 1000; // 简单的hash映射
        }
      }).toList();
    }

     // 生成标题：如果内容太长则截取前50个字符，否则使用内容作为标题
    String title = post.content.length > 50 
        ? '${post.content.substring(0, 50)}...' 
        : post.content;
    
    // 确保标题不为空
    if (title.trim().isEmpty) {
      title = '新帖子'; // 默认标题
    }

    final request = CreatePostRequest(
      userId: imLogic.userInfo.value.userID ?? '',
      circleId: circleId, // 使用映射后的数字ID
      title: title, // 提供有效的标题
      content: post.content,
      images: post.images,
      videos: post.videos, 
      tagIds: tagIds, // 使用从post.tags转换的int数组
      visibility: 'public',
      status: 'published',
       // 新增：位置字段
      locationLatitude: post.locationLatitude,
      locationLongitude: post.locationLongitude,
      locationAddress: post.locationAddress,
    );

    final resp = await Apis.createPost(request);
    debugPrint(resp.toString());
    
    // 直接解析ApiResp格式的响应
    IMViews.showToast('发布成功');
    
    // 可选：更新本地帖子数据
    final serverPost = resp;
    
    // 获取OpenIM用户信息来更新本地帖子
    String userName = serverPost['user']?['name'] ?? post.userName;
    String userAvatar = serverPost['user']?['avatar'] ?? post.userAvatar;
    
    // 尝试从OpenIM获取最新用户信息
    final openimUserId = serverPost['openim_user_id'];
    if (openimUserId != null && openimUserId.isNotEmpty) {
      final openimUserInfo = await _getOpenIMUserInfo(openimUserId);
      if (openimUserInfo.isNotEmpty) {
        userName = openimUserInfo['nickname'] ?? userName;
        userAvatar = openimUserInfo['faceURL'] ?? userAvatar;
      }
    }
    
    // 这里可以根据需要更新post对象的属性
    final postIndex = posts.indexWhere((p) => p.id == post.id);
    if (postIndex != -1) {
      // 创建新的CirclePost对象，使用服务器返回的数据和OpenIM用户信息
      final updatedPost = CirclePost(
        id: serverPost['id']?.toString() ?? post.id, // 使用服务器返回的ID
        userId: serverPost['user_id'] ?? post.userId,
        userName: userName,
        userAvatar: userAvatar,
        content: serverPost['content'] ?? post.content,
        images: List<String>.from(serverPost['images'] ?? post.images),
        // 新增：视频
        videos: List<String>.from(serverPost['videos'] ?? post.videos),
        tags: post.tags, // 保持原有标签
        createdAt: serverPost['created_at'] != null 
            ? DateTime.parse(serverPost['created_at']) 
            : post.createdAt,
        likeCount: serverPost['like_count'] ?? 0,
        commentCount: serverPost['comment_count'] ?? 0,
        shareCount: serverPost['share_count'] ?? 0,
        isLiked: serverPost['is_liked'] ?? false,
        isBookmarked: serverPost['is_bookmarked'] ?? false,
          // 新增：位置
        locationLatitude: (() {
          final v = serverPost['location_latitude'];
          if (v is num) return v.toDouble();
          if (v is String) return double.tryParse(v);
          return post.locationLatitude;
        })(),
        locationLongitude: (() {
          final v = serverPost['location_longitude'];
          if (v is num) return v.toDouble();
          if (v is String) return double.tryParse(v);
          return post.locationLongitude;
        })(),
        locationAddress: serverPost['location_address'] ?? post.locationAddress,
    );
    
    // 更新本地列表中的帖子
    posts[postIndex] = updatedPost;
    }
  } catch (e) {
    IMViews.showToast('发布失败: $e');
    posts.removeWhere((p) => p.id == post.id);
  }
}
  // 根据圈子类型获取圈子ID
  int _getCircleId(CircleType circleType) {
    // 从已加载的圈子数据中查找对应的圈子
    final circle = getCircleByType(circleType);
    if (circle != null) {
      return circle.id;
    }
    
    // 如果没有找到对应的圈子，返回默认值
    switch (circleType) {
      case CircleType.city:
        return 1; // 城市圈默认ID
      case CircleType.country:
        return 2; // 国家圈默认ID
      case CircleType.global:
        return 3; // 全球圈默认ID
    }
  }

  List<PostTag> parseTags(dynamic tagsJson) {
    if (tagsJson == null) return [];
    
    try {
      if (tagsJson is List) {
        return tagsJson
            .map((tagJson) => PostTag.fromJson(tagJson as Map<String, dynamic>))
            .toList();
      }
    } catch (e) {
      print('解析标签数据失败: $e');
    }
    
    return [];
  }
  // 下拉刷新获取最新帖子
  Future<void> refreshPosts(CircleType circleType) async {
    print("开始刷新");
    if (isRefreshing.value) return; // 防止重复刷新
  
    try {
      isRefreshing.value = true;
      // 根据圈子类型调用相应的API
      final response = await Apis.getPostsByCircle(
        circleId: _getCircleId(circleType).toString(),
        page: 1,
        pageSize: 20,
      );
      print("返回值:$response");
      if (response != null) {
        final postsData = response['posts'] as List?;
        debugPrint("postsData:$postsData");
        if (postsData != null) {
          // 清空现有帖子并添加新数据
          posts.clear();
          
          // 第一步：收集所有OpenIM用户ID
          final Set<String> openimUserIds = {};
          for (var postJson in postsData) {
            final openimUserId = postJson['user']['openim_user_id'];
            if (openimUserId != null && openimUserId.isNotEmpty) {
              openimUserIds.add(openimUserId);
            }
          }
          
          // 第二步：批量获取OpenIM用户信息（新增在线兜底）
          Map<String, dynamic> openimUserInfoMap = {};
          if (openimUserIds.isNotEmpty) {
            try {
              // 先尝试从缓存获取
              final cachedList = await OpenIM.iMManager.userManager.getUsersInfoWithCache(openimUserIds.toList());
              final Set<String> missingIds = {};
              for (final userInfo in cachedList) {
                final id = userInfo.userID;
                if (id != null) {
                  final nickname = userInfo.nickname;
                  final faceURL = userInfo.faceURL;
                  openimUserInfoMap[id] = {
                    'nickname': nickname,
                    'faceURL': faceURL,
                  };
                  // debugPrint("faceURL:$faceURL");
                  // 若缓存中头像或昵称为空，则标记在线补拉
                  if ((nickname == null || nickname.isEmpty) || (faceURL == null || faceURL.isEmpty)) {
                    missingIds.add(id);
                  }
                }
              }
              // 将缓存未命中的ID加入在线补拉队列
              for (final id in openimUserIds) {
                if (!openimUserInfoMap.containsKey(id)) {
                  missingIds.add(id);
                }
              }
              // 在线补拉并与缓存结果合并
              if (missingIds.isNotEmpty) {
                final onlineList = await OpenIM.iMManager.userManager.getUsersInfo(userIDList: missingIds.toList());
                for (final userInfo in onlineList) {
                  final id = userInfo.userID;
                  if (id != null) {
                    final nickname = userInfo.nickname ?? userInfo.simpleUserInfo?.nickname;
                    final faceURL = userInfo.faceURL ?? userInfo.simpleUserInfo?.faceURL;
                    debugPrint("faceURL:$faceURL");
                    final existing = openimUserInfoMap[id];
                    openimUserInfoMap[id] = {
                      'nickname': (nickname != null && nickname.isNotEmpty) ? nickname : (existing?['nickname']),
                      'faceURL': (faceURL != null && faceURL.isNotEmpty) ? faceURL : (existing?['faceURL']),
                    };
                  }
                }
              }
              debugPrint('Loaded ${openimUserInfoMap.length} user info (cache+online) in refreshPosts');
            } catch (e) {
              debugPrint('Failed to batch load user info (cache/online) in refreshPosts: $e');
            }
          }
          
          // 第三步：创建帖子对象，使用OpenIM信息或后端数据作为备选
          for (var postJson in postsData) {
            final openimUserId = postJson['user']['openim_user_id'];
            debugPrint("openimUserId:$openimUserId");
            // 优先使用OpenIM信息，如果没有则使用后端数据
            String userName = postJson['user']?['nickname'] ?? '未知用户';
            String userAvatar = postJson['user']?['avatar'] ?? '';
            
            if (openimUserId != null && openimUserInfoMap.containsKey(openimUserId)) {
              final openimInfo = openimUserInfoMap[openimUserId];
              userName = openimInfo['nickname'] ?? userName;
              userAvatar = openimInfo['faceURL'] ?? userAvatar;
            }
            debugPrint("userAvatar:$userAvatar");
            // 将后台数据转换为CirclePost对象
            final post = CirclePost(
              id: postJson['id'].toString(),
              userId: postJson['user_id'] ?? '',
              userName: userName,
              userAvatar: userAvatar,
              content: postJson['content'] ?? '',
              // 新增：从后端解析图片与视频
              images: List<String>.from(postJson['images'] ?? []),
              videos: List<String>.from(postJson['videos'] ?? []),
              tags: parseTags(postJson['tags']), // 使用解析方法
              createdAt: DateTime.tryParse(postJson['created_at'] ?? '') ?? DateTime.now(),
              likeCount: postJson['like_count'] ?? 0,
              isLiked: postJson['is_liked'] ?? false,
              isBookmarked: postJson['is_collected'] ?? false,
              commentCount: postJson['comment_count'] ?? 0,
              shareCount: postJson['share_count'] ?? 0,
              // 添加圈子信息字段
              circleId: postJson['circle_id'],
              circleName: postJson['circle']['name'],
              circleType: _mapCircleTypeFromString(postJson['circle']['type'].toString()),

              // 新增：位置字段解析
              locationLatitude: (() {
                final v = postJson['location_latitude'];
                if (v is num) return v.toDouble();
                if (v is String) return double.tryParse(v);
                return null;
              })(),
              locationLongitude: (() {
                final v = postJson['location_longitude'];
                if (v is num) return v.toDouble();
                if (v is String) return double.tryParse(v);
                return null;
              })(),
              locationAddress: postJson['location_address'],
              
            );
            debugPrint("current:$post");
            posts.add(post);
          }
        }
        // IMViews.showToast('刷新成功');
      } else {
        print("刷新失败: 响应为空");
        IMViews.showToast('刷新失败: 响应为空');
      }
    } catch (e) {
      print("刷新异常: $e");
      IMViews.showToast('刷新失败: $e');
    } finally {
      isRefreshing.value = false;
    }
  }
 
  CircleType _mapCircleTypeFromString(String typeString) {
    switch (typeString.toLowerCase()) {
      case 'city':
        return CircleType.city;
      case 'country':
        return CircleType.country;
      case 'global':
        return CircleType.global;
      default:
        return CircleType.city;
    }
  }
  /// 刷新标签数据（可在需要时调用）
  Future<void> refreshTags() async {
    await loadTagsFromBackend();
  }
  
  Future<void> onTabSwitched() async {
    print('通知tab被点击，开始刷新数据');
    // 刷新标签数据
    await refreshTags();
    // 当通知tab被点击时，刷新当前圈子类型的帖子
    refreshPosts(currentCircleType.value);
  }

  // 获取通知显示的文本内容
  String getNotificationDisplayText(PostNotification notification) {
    final displayName = getNotificationDisplayName(notification);
    switch (notification.type) {
      case NotificationType.like:
        return '$displayName 赞了你的帖子';
      case NotificationType.comment:
        return '$displayName 评论了你的帖子';
      case NotificationType.reply:
        return '$displayName 回复了你';
      case NotificationType.mention:
        return '$displayName 在帖子中提到了你';
      case NotificationType.follow:
        return '$displayName 关注了你';
      case NotificationType.system:
        return notification.content;
    }
  }

  /// 根据OpenIM ID获取用户信息的辅助方法
  Future<Map<String, String?>> _getOpenIMUserInfo(String openimUserId) async {
    try {
      final userInfoList = await OpenIM.iMManager.userManager.getUsersInfoWithCache([openimUserId]);
      if (userInfoList.isNotEmpty) {
        final userInfo = userInfoList.first;
        return {
          'nickname': userInfo.nickname,
          'faceURL': userInfo.faceURL,
        };
      }
    } catch (e) {
      debugPrint('Failed to get OpenIM user info for $openimUserId: $e');
    }
    return {};
  }

  /// 公共方法：刷新指定帖子的用户信息（供其他地方调用）
  Future<void> refreshPostUserInfo(String postId, String openimUserId) async {
    final userInfo = await _getOpenIMUserInfo(openimUserId);
    if (userInfo.isNotEmpty) {
      final postIndex = posts.indexWhere((post) => post.id == postId);
      if (postIndex != -1) {
        posts[postIndex] = posts[postIndex].copyWith(
          userName: userInfo['nickname'] ?? posts[postIndex].userName,
          userAvatar: userInfo['faceURL'] ?? posts[postIndex].userAvatar,
        );
        update();
        debugPrint('Refreshed user info for post $postId');
      }
    }
  }
}